
var express = require('express');
var router = express.Router();
var User=require('../models/user.server.model.js');
var News=require('../models/news.server.model.js');
router.get('/admin-index.html',function(req,res,next){
    News.find(function(error,docs){
         if(error){
             return res.send('error');
         }

        //res.json(docs)
        res.render('admin/admin-index', { title: 'JSON博客',lists:docs });
    });
    //
});
router.get('/admin-table.html',function(req,res,next){
    res.render('admin/admin-table', { title: 'JSON博客' });
});
router.get('/admin-form.html',function(req,res,next){
    res.render('admin/admin-form', { title: 'JSON博客' });
});
//发布文章表单
router.post('/do-admin-form.html',function(req,res,next){

    var post=req.body;
    var news=new News({
        category:post.category,
        status:post.status,
        type:post.type
    });
    news.save(function(err){
        if(err){
            res.json('eeee');
        }
        return res.redirect('admin-index.html');
    });

    //res.render('admin/admin-form', { title: 'JSON博客' });
});



/* GET home page. */
router.get('/', function(req, res, next) {
    console.log("1111")
    res.render('index', { title: 'JSON博客' });
});
router.get('/index.html', function(req, res, next) {

    res.render('index', { title: 'JSON博客' });
});
router.get('/login.html', function(req, res, next) {
    res.render('login', { title: '登录1',msg:'' });
});
router.post('/dologin.html', function(req, res, next) {
    var post=req.body;
    User.findOne({username:post.username},function(error,docs){
        if(error){
            res.send(error);
        }
        if(docs!=null && post.password==docs.password){
            req.session.username=post.username;
            return res.redirect('/admin.html');
        }else{
            res.render('login', { title: '登录',msg:'帐号或密码错误' });
             res.end()
        }
    });

});
router.get('/admin.html', function(req, res, next) {

    res.render('admin', { title: '注册',username:req.session.username });
});
router.get('/register.html', function(req, res, next) {

    res.render('register', { title: '注册' });
});
router.post('/doregister.html', function(req, res, next) {
    post=req.body;
    if(!post.username||!post.password)
    res.send('error');
    var user=new User({
        username:post.username,
        password:post.password
    });
    user.save(function(err){
        if(err)res.send('add error');
        res.redirect('/login.html');
    })
    //res.render('register', { title: '注册' });
});
router.get('/post.html', function(req, res, next) {
    res.render('post', { title: '发贴' });
});

module.exports = router;

